package com.rxz.redisdemo.config;

import com.rxz.redisdemo.common.RedisCommon;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (token == null){
            response.setStatus(401);
            return false;
        }
        // 基于token获取redis中的信息
        String tokenKey = RedisCommon.REIDS_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        if(userMap.isEmpty()){
            response.setStatus(401);
            return false;
        }
        // 刷新token有效期
        stringRedisTemplate.expire(tokenKey,RedisCommon.REDIS_TTL, TimeUnit.MINUTES);
        // 放行
        return true;
    }
}
